extends GlobalArea
class_name BaseEnemy
signal harm(size : int)
signal reset_enemy_path(enemy : BaseEnemy)
@onready var attack_interval_timer: Timer = $AttackIntervalTimer
@onready var model: Sprite2D = $Model
@onready var attack_area: Area2D = $Model/AttackArea
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var animation_player_2: AnimationPlayer = $AnimationPlayer2

@export var enemy_item : EnemyItem
var current_health : int
var attack_target : Node2D
var path : Array
var is_attack : bool

func _ready() -> void:
	super()
	_init_item()
	_init_attack_interval_timer()
	_init_signal()

func _process(_delta: float) -> void:
	_death()

func _physics_process(_delta: float) -> void:
	if not is_attack : return
	if path :
		var end_point = path.front()
		var tween = create_tween()
		#tween.tween_property(self, "look_at", end_point, 0.2)
		var direction = end_point - global_position
		var target_rotation = direction.angle()
		tween.tween_property(self, "rotation", target_rotation, 0.3)
		global_position = global_position.move_toward(end_point, enemy_item.move_speed * _delta)
		if global_position == end_point :
			path.remove_at(0)
	if not path : 
		call_deferred("_check_attack_target")

func _init_item() -> void :
	current_health = enemy_item.health_max

func _init_signal() -> void :
	harm.connect(_on_harm)
	GlobalVariable.main.on_start.connect(_begin_show)
	GlobalVariable.main.on_end.connect(_end_hide)

func _init_attack_interval_timer() -> void :
	attack_interval_timer.timeout.connect(_enemy_attack)
	attack_interval_timer.wait_time = enemy_item.attack_interval
	attack_interval_timer.start()

func _set_attack(_path : Array = [], ready_pos : Vector2 = global_position) -> void :
	is_attack = true
	path = _path
	global_position = ready_pos

func _check_attack_target() -> void :
	var build_list = attack_area.get_overlapping_areas()
	if build_list :
		attack_target = build_list.get(0)
		if not attack_target.is_in_group("base_build") : return
		var direction = attack_target.global_position - global_position
		var target_rotation = direction.angle()
		var tween = create_tween()
		tween.tween_property(self, "rotation", target_rotation, 0.3)
		#look_at(attack_target.global_position)
	else :
		is_attack = false
		reset_enemy_path.emit(self)

func _enemy_attack() -> void :
	if path : return
	if not attack_target : return
	animation_player.play("attack")
	attack_target.harm.emit(enemy_item.attack_size)

func _on_harm(size : int) -> void :
	current_health -= size
	animation_player_2.play("harm")

func _death() -> void :
	if current_health <= 0 :
		queue_free()

func _begin_show() -> void :
	pass

func _end_hide() -> void :
	pass
